package dao;

import entity.Card;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CardDao extends BaseDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    /**
     * 查询所有
     * @return
     */
    public List<Card> cardList(){
        conn = super.getConnection();
        List<Card> list = new ArrayList<>();
        Card card = null;
        try{
            String sql = "select * from card order by createDate desc";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                card = new Card();
                card.setId(rs.getInt("id"));
                card.setUserName(rs.getString("userName"));
                card.setIdNumber(rs.getString("idNumber"));
                card.setCreateDate(rs.getString("createDate"));
                card.setStatus(rs.getInt("status"));
                list.add(card);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return list;
    }

    public Boolean cardSelectIdNumber(String idNumber){
        conn = super.getConnection();
        boolean flag = false;
        try{
            String sql = "select idNumber from card where idNumber=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,idNumber);
            rs = ps.executeQuery();
            if(rs.next()){
                flag = true;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return flag;
    }

    public int cardAdd(Card card){
        conn = super.getConnection();
        int i = 0;
        try{
            String sql = "insert into card(userName, idNumber, status, createDate) VALUES (?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,card.getUserName());
            ps.setString(2,card.getIdNumber());
            ps.setInt(3,card.getStatus());
            ps.setString(4,card.getCreateDate());
            i = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return i;
    }

    /**
     * 修改
     * @param status
     * @return
     */
    public int cardUpdate(int status,int id){
        conn = super.getConnection();
        int i = 0;
        try{
            String sql = "update card set status=? where id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,status);
            ps.setInt(2,id);
            i = ps.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.closeAll(conn,ps,rs);
        }
        return i;
    }
}
